package com.greatmay.webapp.servlet;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class MashupServlet extends HttpServlet{
	private static final long serialVersionUID = 3437315775306867627L;
	public static final String URL = "url";
	private static final Log log = LogFactory.getLog(MashupServlet.class);
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		String urlStr = request.getParameter(URL);
		if (StringUtils.isEmpty(urlStr)) {
			log.error("url is empty. " + request.getRequestURL().toString());
			try {
				response.getWriter().write("无法读取。请联系管理员。");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(urlStr);
		try {
			client.executeMethod(method);
		    Reader reader = new InputStreamReader(
		            method.getResponseBodyAsStream(), "UTF-8"); 
		    int l;
		    char[] cbuf = new char[1024];
		    Writer w = response.getWriter();
			while ((l = reader.read(cbuf)) != -1) {
				w.write(cbuf,0,l);
			}
			w.flush();
		} catch (HttpException e) {
			log.error("url is empty. " + request.getRequestURL().toString());
			try {
				response.getWriter().write("无法读取。请联系管理员。");
			} catch (IOException ex) {
				ex.printStackTrace();
			}
			e.printStackTrace();
		} catch (IOException e) {
			log.error("url is empty. " + request.getRequestURL().toString());
			try {
				response.getWriter().write("无法读取。请联系管理员。");
			} catch (IOException ex) {
				ex.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	
	public static void main(String[] a) throws HttpException, IOException {
	String urlStr = "http://localhost/gm/main.shtml";
	HttpClient client = new HttpClient();
	GetMethod method = new GetMethod(urlStr);
	System.out.println(client.executeMethod(method));
	System.out.println(Arrays.toString(method.getResponseHeaders()));
	System.out.println(method.getResponseCharSet());
    Reader reader = new InputStreamReader(
            method.getResponseBodyAsStream(), "UTF-8"); 
    int l;
    char[] cbuf = new char[1024];
    Writer w = new OutputStreamWriter(System.out);
	while ((l = reader.read(cbuf)) != -1) {
		w.write(cbuf,0,l);
	}
	w.flush();
	}
}
